<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 有时间可以考虑各用户类型(artist,model,ins,merchant)从此类扩展下来
 * 当前用户类可以做好 各类用户 的公共实现，并为用户类型做好定义，方便多态实现
 * 各子类可以将自身 用户类型 设定在属性中，这样方便对此类型做相应的动作
 */

class User_model extends Xt_model {

	protected $mTable = 'user';
	protected $tb_user = 'user';
	protected $tb_userdetail = 'user_detail';
	protected $tb_usermemo = 'user_memo';
    private $tb_userbody = 'user_body';
    protected $tb_sms_code = "sms_code";
    //用户挂起状态定义 0显示;1暂停
    var $field_hangup_status = array('show'=>1,'unshow'=>-1);
    var $field_hangup_status_name = array('show'=>'显示', 'unshow'=>'暂停');
    //用户状态定义 -1已删除;1正常;2禁止登录
    var $field_user_status = array('deleted'=>-1,'normal'=>1, 'disable'=>2);
	var $usertype_name = array(//这里指定用户类型对应的模块, 没有创建模块文件前暂不设定值,也可以做为用户类型英文名称
		1 => 'model',
		2 => '',//'ins',
		3 => '',//'merchant',
		4 => '',
		5 => '',
		6 => '',//'artist'
	);

	public function get_info_by_id($id, $fields='*')
	{
		$aUser = $this->get_by_id($id, $fields);
		$aUser = $aUser?$aUser:array();
		// if( in_array($aUser['usertype'],array(1,4,5)) )
		// {
			$this->set_table($this->tb_userdetail);
			$aUserDetail = $this->get_by_where("userid=$id",'*');
			if($aUserDetail)
				$aUser = array_merge($aUserDetail, $aUser);
			$this->set_table($this->tb_usermemo);
			$aUserMemo = $this->get_by_where("userid=$id",'*');
			if($aUserMemo)
				$aUser = array_merge($aUserMemo, $aUser);
			$this->set_table($this->tb_user);
			return $aUser;
		// }
		// else
		// {
		// 	$this->set_table($this->tb_usermemo);
		// 	$aUserMemo = $this->get_by_where("userid=$id",'*');
		// 	if($aUserMemo)
		// 		$aUser = array_merge($aUserMemo, $aUser);
		// 	$this->set_table($this->tb_user);
		// 	return $aUser;
		// }

		/*$rs = $this->db->select($fields)
		->from($this->mTable.' a')
		->join($this->tb_userdetail.' b','a.id=b.userid','left')
		->join($this->tb_usermemo.' c','a.id=c.userid','left')
		->where("a.id=$id")
		->get()->row_array();
		print_r($rs);die;
		return $rs;
		*/
	}


	public function get_user_by_username($username, $fields='*')
	{
		$db_temp = $this->db->select($fields)
		->from($this->mTable)
		->where('username', $username)
		->get()
		->row_array();
		echo $this->db->last_query();
		die;
		return $db_temp;
	}

	public function get_user_by_nickname($nickname, $fields='*')
	{
		$db_temp = $this->db->select($fields)
		->from($this->mTable)
		->where('nickname', $nickname)
		->get()
		->row_array();
		return $db_temp;
	}

	public function get_user_by_mobile($mobile, $fields='*')
	{
		$db_temp = $this->db->select($fields)
		->from($this->mTable)
		->where('mobile', $mobile)
		->get()
		->row_array();
		return $db_temp;
	}

	public function get_user_by_email($email, $fields='*')
	{
		$db_temp = $this->db->select($fields)
		->from($this->mTable)
		->where('email', $email)
		->get()
		->row_array();
		return $db_temp;
	}

	

	public function login_update($id, $last_datetime, $last_ip)
	{
		$this->db->set('lastlogintime', $last_datetime, FALSE);
		$this->db->set('lastip', $last_ip, FALSE);
		//$this->db->set('login_num', 'login_num+1', FALSE);
		//$this->db->set('security_code', $this->security_code);
		$this->db->where('id', $id);
		return $this->db->update($this->mTable);
	}

	/**
	*更新email
	*/
	public function email_update($id, $email, $email_true){
		if(empty($id)) return 0;

		$email_true=($email_true==1)?1:0;
		if($email){
			$this->db->set('email', $email);
		}
		//$this->db->set('email_true', $email_true, FALSE);
		$this->db->where('id', $id);
		return $this->db->update($this->mTable);
	}

	/**
	*通过用户表id更新
	*/
	public function update_info_by_id($id, $data, $data_detail=array(), $data_memo=array(), $data_body = array())
	{
                
        if (!empty($data_body)) 
        {
           // 体型参数
           $data_body['userid'] = $id;
           $this->set_table($this->tb_userbody);
           $this->insert($data_body);
        }
                
		if(!empty($data_detail))
		{
            //详情
            $this->set_table($this->tb_userdetail);
            $this->update_by_where(array('userid'=>$id), $data_detail, $this->tb_userdetail);
		}
		if(!empty($data_memo))
		{
            // 图片设置
            $this->set_table($this->tb_usermemo);
            $this->update_by_where(array('userid'=>$id), $data_memo, $this->tb_usermemo);
		}
		$this->set_table($this->tb_user);

		return $this->update_by_id($id, $data);
	}

	public function get_user_by_ids($id, $fields = "*")
	{
		$db_temp = $this->db->select($fields)
		->from($this->mTable)
		->where_in('id', $id)
		->get()
		->result_array();
		return $db_temp;
	}

	public function user_nickname_check($val)
	{
		$db_temp = $this->db->select('count(1) as num ',false)
		->from($this->mTable)
		->where('nickname', $val)
		->get()
		->row_array();
		return $db_temp['num'];
	}

	public function user_mobile_check($val)
	{
		$db_temp = $this->db->select('count(1) as num ',false)
		->from($this->mTable)
		->where('mobile', $val)
		->get()
		->row_array();
		return $db_temp['num'];
	}

	public function user_email_check($val)
	{
		$db_temp = $this->db->select('count(1) as num ',false)
		->from($this->mTable)
		->where('email', $val)
		->get()
		->row_array();
		return $db_temp['num'];
	}

	public function user_username_check($val)
	{
		$db_temp = $this->db->select('count(1) as num ',false)
		->from($this->mTable)
		->where('username', $val)
		->get()
		->row_array();
		return $db_temp['num'];
	}

	public function add_user_by_ins($insid,$usertype)
	{
		$data = array('username'=>time(),
			'usertype'=>$usertype,
			'insid'=>$insid,
			'status'=>2,		//无登录功能
			'addtime'=>time(),
			'lastip'=>_ip_long(),
			);
		$userid = $this->insert_string( $data );

		$data_detail = array('userid'=>$userid,
			);
		$data_memo = array('userid'=>$userid,
			);
		$this->set_table($this->tb_userdetail);
        $this->insert($data_detail);
        $this->set_table($this->tb_usermemo);
        $this->insert($data_memo);
        $this->set_table($this->tb_user);

        return $userid;
	}
	
	/**
	 * 根据手机号获取最新的验证码
	 * @param string $mobile
	 */
	public function getMobileSmsCode($mobile)
	{
		$this->set_table($this->tb_sms_code);
		$where = array("mobile"=>$mobile);
		$list = $this->get_list($where,"code","created desc",1);
// 		echo $this->db->last_query();die;
		return $list?$list[0]["code"]:'';
	}
	
	/**
	 * 获取用户个数
	 * @param array $arrWhere
	 */
	public function getUserCount($arrWhere)
	{
		$this->set_table($this->tb_user);
		return $this->count($arrWhere);
	}
	
	//根据微博uid获取用户信息
	public function get_user_by_weibouid($weibo_uid, $fields='*')
	{
		$db_temp = $this->db->select($fields)
		->from($this->mTable)
		->where('weibo_uid', $weibo_uid)
		->get()
		->row_array();
		return $db_temp;
	}
	
	//根据QQ openid获取用户信息
	public function get_user_by_qqopenid($openid, $fields='*')
	{
		$db_temp = $this->db->select($fields)
		->from($this->mTable)
		->where('qq_openid', $openid)
		->get()
		->row_array();
		return $db_temp;
	}

    /** 根据机构id取得旗下艺人
     * @param $insid 机构id
     * @return $db_temp 数据集(二维数组)
    */
    public function get_users_by_ins($insid, $fields = "*")
    {
        $db_temp = $this->db->select($fields)
            ->from($this->mTable)
            ->where('insid', $insid)
            ->get()
            ->result_array();
        return $db_temp;
    }

    /** 根据用户id 挂起 或 解挂
     * @param $userid 用户id
     * @param $show_status 挂起状态
    */
    public function hangup_by_uid($userid, $show_status='unshow'){
        /**
         * 先判断用户是否为机构
         * 1. 如果为机构则先挂起旗下艺人，再挂起机构
         * 2. 如果为 机构 或 艺人 则查询出发布的通告，并将通告状态变更为 删除 状态
         * 3. 如果为个人用户则直接挂起
        */
        $uidlist = array();//要变更状态的用户列表
        $u_info = $this->get_info_by_id($userid,"usertype, hangup_status,insid");
        if (!$u_info) {
            return false;
        }
        //如果是机构，如果旗下有艺人，先挂起旗下艺人
        if (in_array($u_info['usertype'], array(2)) && $rs = $this->get_users_by_ins($userid, 'id')){
            foreach ($rs as $k=>$v){
                $uidlist[] = $v['id'];
            }
        }
        if ($u_info['insid']) {//如果当前设置的用户为 机构 的 旗下艺人，则先判断 机构 是否为 暂停状态
            $ins_user = $this->get_info_by_id($u_info['insid'],"usertype, hangup_status");
            if (array_search($ins_user['hangup_status'],$this->field_hangup_status)=='unshow') {
                return false;
            }
        }
        //事务开始
        $this->db->trans_start();
		/*
		 * 这里暂时不做此功能实现, 原因是 通告展示页 已经对 已删除 或 已暂停 的用户做了过滤处理
		 * 不用设置 display 项也不会展示到网站前台了
        //如果是机构、企业 或 艺人，更新用户发布的通告的 显示状态 为 不显示
        $this->load->model('User_oplog_model');
        $this->load->model('Activity_model');
        if (in_array($u_info['usertype'], $this->Activity_model->usertype)) {
            $set_data = array('display'=>2);
            //$this->Activity_model->update_by_where(array('userid'=>$userid), $set_data);
            //记录信息变更的日志
            //$this->User_oplog->insert_oplog("activity",'update', $set_data, array('userid'=>$userid));
        }
		*/
        $uidlist[] = $userid; //将 机构 或 艺人 加入到要变更状态的用户列表中
        //更新状态，0为展示，1为挂起
        $hangup_status = $this->field_hangup_status[$show_status];
        $this->db->set('hangup_status', $hangup_status);
        $this->db->where_in('id', $uidlist);
        $this->db->update($this->mTable);
        //记录信息变更的日志
        $this->load->model('User_oplog_model');
        $this->User_oplog_model->insert_oplog("user",'update', array('hangup_status'=>$hangup_status), array('id'=>implode(',',$uidlist)));
        $this->db->trans_complete();
        //事务结束

        return true;
    }

    /**
     * 取得所有 已经删除 或 已经暂停 的用户id列表
     * @param $type 获取类型：all,hangup,status
     * @param $justuid 是否返回UID列表
    */
    public function get_unshow_users($type='all',$justuid=false) {
        $where = array();
        switch ($type){
            case 'hangup':
                $where['hangup_status'] = $this->field_hangup_status['unshow'];
                break;
            case 'status':
                $where['status'] = $this->field_user_status['deleted'];
                break;
            default:
                $where['status='] = "'{$this->field_user_status['deleted']}' or hangup_status='{$this->field_hangup_status['unshow']}'";
                break;
        }
        $userlist = $this->list_by_where($where);
        if ($justuid) {
            $uidlist = array();
            foreach ($userlist as $val) {
                $uidlist[] = $val['id'];
            }
            $userlist = $uidlist;
        }
        return $userlist;
    }
    /**
     * 取得暂停处理的反面值
     * @param $cur_status 当前状态值 show/unshow
    */
    public function get_hangup_status_obverse($cur_status){
        $re_status = $this->User_model->field_hangup_status[$cur_status];
        return array_search(-$re_status,$this->User_model->field_hangup_status);
    }

	/**
	 * 获取用户标签方法
	*/
	public function get_label() {}
}
